package com.kgc.search.service.impl;

import com.kgc.dao.TbItemMapper;
import com.kgc.search.service.ItemSolrService;
import com.kgc.utils.ItripResult;
import com.kgc.utils.SearchItem;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import com.kgc.utils.SearchResult;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ItemSolrServiceImpl implements ItemSolrService {

    @Value("${pageSize}")
    private int pageSize;
    @Autowired
    private SolrServer solrServer;

    @Autowired
    private TbItemMapper itemMapper;
    @Override
    public ItripResult searchAllItemToSolr() {

        //查询出所有商品
        List<SearchItem> list = itemMapper.searchAll();
        //将商品增加solr中
try {
    for (SearchItem item : list) {
        SolrInputDocument solrDocument = new SolrInputDocument();
        solrDocument.addField("id",item.getId());
        solrDocument.addField("item_title",item.getTitle());
        solrDocument.addField("item_sell_point", item.getSellPoint());
        solrDocument.addField("item_price", item.getPrice());
        solrDocument.addField("item_category_name", item.getCategoryName());
        solrDocument.addField("item_image",item.getImage());
        solrServer.add(solrDocument);
    }
    solrServer.commit();
}catch (Exception ex){
    ex.printStackTrace();
}
        return ItripResult.ok();
    }


    @Override
    public SearchResult queryItemSolr(String q, int page)  throws Exception{

        SearchResult searchResult=new SearchResult();
        List<SearchItem> items=new ArrayList<>();
        SolrQuery query = new SolrQuery();

        query.set("df", "item_keywords");
        query.setQuery(q);//如果item_title  sell_point  cate_name
        query.addSort("item_price", SolrQuery.ORDER.desc);//价格
        //启用分页
        query.setStart((page-1)*pageSize);//启始行号
        query.setRows(pageSize);//每页的记录数

        query.setHighlight(true);//开高亮设置
        query.addHighlightField("item_title");//只对title作高亮
        query.addHighlightField("item_sell_point");

        query.setHighlightSimplePre("<font color='red'>");
        query.setHighlightSimplePost("</font>");

        QueryResponse response = solrServer.query(query);
        SolrDocumentList results = response.getResults();
       // System.out.println("总记录数:" + results.getNumFound());
       //  searchResult.setCount(results.getNumFound());
         Long rows=results.getNumFound();
         if(rows % pageSize==0)
             searchResult.setTotalPages(rows/pageSize);
         else
             searchResult.setTotalPages(rows/pageSize+1);
        for (SolrDocument doc : results) {
            String id = doc.get("id").toString();//
            String title = doc.getFieldValue("item_title").toString();
            String sellPoint = doc.get("item_sell_point").toString();

            //得到response中所有高亮的数据
            Map<String, Map<String, List<String>>> highlight = response.getHighlighting();
            //外层的map有10个key-value  id为1002   Map  1002这个document所有高亮的数据
            Map<String, List<String>> map1 = highlight.get(id);
            List list1 = map1.get("item_title");
            if (list1 != null) {
                title = list1.get(0).toString();
            }

            List list2 = map1.get("item_sell_point");
            if (list2 != null) {
                sellPoint = list2.get(0).toString();
            }
            String price = doc.get("item_price").toString();
            String[] images=null;
            if(doc.get("item_image").toString()!=null && doc.get("item_image").toString().length()>0) {
                images= doc.get("item_image").toString().split(",");
            }
            String image=null;
            if(images!=null&&images.length>0){
                image=images[0];
            }else{
                image="http://192.168.25.133/group1/M00/00/03/wKgZhV-zVM2ABinpACX40PqxXZY618.JPG";
            }
            String caName=doc.get("item_category_name").toString();
            SearchItem searchItem=new SearchItem();
            searchItem.setId(id);
            searchItem.setTitle(title);
            searchItem.setCategoryName(caName);
            searchItem.setImage(image);
            searchItem.setPrice(Long.parseLong(price));
           searchItem.setSellPoint(sellPoint);
           items.add(searchItem);
        }
        searchResult.setItemList(items);
       return searchResult;
    }
}
